package cmu.mobile.lab;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.text.GetChars;


public class ImageLoader {
	
	private static final String SDCARD_FASHIONISTA_IMAGES = "/sdcard/FashionistaImages/";
	private final static String SERIALIZATION_DELIMITER = "BASDKFHGBSADF";
	private static ImageLoader il;

	private ImageLoader () {

	}

	public static ImageLoader getImageLoader() {
		if (il == null) 
			il = new ImageLoader();
		return il;
	}

	public static boolean uploadItem(String path, MMSContent item, String id)  {
		HttpURLConnection connection = null;
		DataOutputStream outputStream = null;
		DataInputStream inputStream = null;

		// change this?
		String urlServer = "http://www.gotow.net/fashonista/upload.php?id=" + id
		+ "&extra=" + serializeItem(item);
		String lineEnd = "\r\n";
		String twoHyphen = "--";
		String boundary =  "*****";

		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1*1024*1024;

		try {
			FileInputStream fileInputStream = new FileInputStream(
					new File(path));
			URL url = new URL(urlServer);
			connection = (HttpURLConnection) url.openConnection();

			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);

			connection.setRequestMethod("POST");

			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type", 
					"multipart/form-data;boundary="+boundary);

			outputStream = new DataOutputStream(connection.getOutputStream());
			outputStream.writeBytes(twoHyphen + boundary + lineEnd);
			outputStream.writeBytes("Content-Disposition: form-data; " +
					"name=\"uploadedfile\";filename=\"" + path +"\"" + lineEnd);
			outputStream.writeBytes(lineEnd);

			//below here double check
			bytesAvailable = fileInputStream.available();
			bufferSize = Math.min(bytesAvailable, maxBufferSize);
			buffer = new byte[bufferSize];

			// Read file
			bytesRead = fileInputStream.read(buffer, 0, bufferSize);

			while (bytesRead > 0) {
				outputStream.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}

			outputStream.writeBytes(lineEnd);
			outputStream.writeBytes(twoHyphen + boundary + twoHyphen + lineEnd);

			// Responses from the server (code and message)
			int serverResponseCode = connection.getResponseCode();
			String serverResponseMessage = connection.getResponseMessage();

			fileInputStream.close();
			outputStream.flush();
			outputStream.close();
			
			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return false;
	}

	public static MMSContent downloadItem(String id) {
		MMSContent item = new MMSContent();
		String imageUrl = "http://www.gotow.net/fashonista/" +
				"getImage.php?id=" + id;
		String extrasUrl = "http://www.gotow.net/fashonista/" +
		"getExtras.php?id=" + id;
		String extras = null;
		try {
			DefaultHttpClient client = new DefaultHttpClient();
			URI uri = new URI(extrasUrl);
			HttpGet method = new HttpGet(uri);
			HttpResponse res = client.execute(method);
			InputStream data = res.getEntity().getContent();
			extras = generateString(data);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		item = deserializeItem(extras);
		
		URL myFileUrl = null;
		Bitmap bmImg = null;
		try {
			myFileUrl= new URL(imageUrl);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();

			bmImg = BitmapFactory.decodeStream(is);
			File directory = new File(SDCARD_FASHIONISTA_IMAGES);
			boolean poo = directory.mkdirs();
			String filename = item.getOwnerID() + 
					"Q" + item.getItemID();
			File imageFile = new File(directory, filename);
			FileOutputStream out = new FileOutputStream(imageFile);
			bmImg.compress(Bitmap.CompressFormat.JPEG, 100, out);
			item.setImagePath(SDCARD_FASHIONISTA_IMAGES + filename);
		} catch (IOException e) {
			e.printStackTrace(); 	
		}

		return item;		
	}

	
	public static String generateString(InputStream stream) {
		InputStreamReader reader = new InputStreamReader(stream);
		BufferedReader buffer = new BufferedReader(reader);
		StringBuilder sb = new StringBuilder();

		try {
			String cur;
			while ((cur = buffer.readLine()) != null) {
				sb.append(cur + "\n");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			stream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sb.toString();
	}


	private static String serializeItem(MMSContent item) {
		String stuff = item.getItemID() + SERIALIZATION_DELIMITER + item.getMessageText() +
			SERIALIZATION_DELIMITER + item.getOwnerID() + 
			SERIALIZATION_DELIMITER + item.getPrice() + SERIALIZATION_DELIMITER 
			+ item.getReceiverID() + SERIALIZATION_DELIMITER + item.getSize() +
			SERIALIZATION_DELIMITER + item.getStore();
		stuff = URLEncoder.encode(stuff);
		return stuff;
	}
	
	private static MMSContent deserializeItem(String extra) {
		if (extra == null)
			return null;
		MMSContent item = new MMSContent();
		
		extra = URLDecoder.decode(extra);
		String[] parts = extra.split(SERIALIZATION_DELIMITER);
		item.setItemID(Integer.parseInt(parts[0]));
		item.setMessageText(parts[1]);
		item.setOwnerID(parts[2]);
		item.setPrice(parts[3]);
		item.setReceiverID(parts[4]);
		item.setSize(parts[5]);
		item.setStore(parts[6]);

		return item;
	}

}
